package com.pangu.core.engine.game.task.niuniu;

import java.util.List;

import org.cache2k.expiry.ValueWithExpiryTime;

import com.pangu.core.BMDataContext;
import com.pangu.core.cache.CacheHelper;
import com.pangu.core.engine.game.ActionTaskUtils;
import com.pangu.core.engine.game.BeiMiGameEvent;
import com.pangu.core.engine.game.BeiMiGameTask;
import com.pangu.core.engine.game.task.AbstractTask;
import com.pangu.util.GameUtils;
import com.pangu.util.rules.model.Board;
import com.pangu.util.rules.model.GameStatus;
import com.pangu.web.model.GameRoom;
import com.pangu.web.model.PlayUserClient;

import lombok.extern.slf4j.Slf4j;

/**
 * @ClassName: BeginTask
 * @Description:  开始游戏
 * @author 老王
 * @date 2018年3月27日 下午4:09:49
 *
 */
@Slf4j
public class NiuniuBeginTask extends AbstractTask implements ValueWithExpiryTime, BeiMiGameTask {

	@Override
	public void execute() {
		/******* 更新状态，通知前端 *******/
		gameRoom.setStatus(BMDataContext.GameStatusEnum.BETOVER.toString());
		gameRoom.setStatusTime(System.currentTimeMillis());
		CacheHelper.getGameRoomCacheBean().put(gameRoom.getId(), gameRoom, gameRoom.getOrgi());
		
		GameStatus status = new GameStatus(BMDataContext.GameStatusEnum.BETOVER.toString(), "停止下注");
		ActionTaskUtils.sendEvent(status.getCommand(), status, gameRoom);
		CacheHelper.getGameStatusCacheBean().put(gameRoom.getRoomid(), status, gameRoom.getOrgi());
		/******* 更新状态，通知前端 end *******/
		List<PlayUserClient> playerList = CacheHelper.getGamePlayerCacheBean().getCacheObject(gameRoom.getId(), orgi);
		// 这个时候返回了洗好的牌
		Board board = GameUtils.playGame(playerList, gameRoom, gameRoom.getLastwinner(), gameRoom.getCardsnum());
		CacheHelper.getBoardCacheBean().put(gameRoom.getId(), board, gameRoom.getOrgi());
		for (Object temp : playerList) {
			PlayUserClient playerUser = (PlayUserClient) temp;
			playerUser.setGamestatus(BMDataContext.GameStatusEnum.PLAYING.toString());
			/**
			 * 更新状态到 PLAYING
			 */
			if (CacheHelper.getApiUserCacheBean().getCacheObject(playerUser.getId(), playerUser.getOrgi()) != null) {
				CacheHelper.getApiUserCacheBean().put(playerUser.getId(), playerUser, orgi);
			}
		}
		board.setPlayers(null);
		board.setCommand(BMDataContext.BEIMI_GAME_LASTHANDS);
		ActionTaskUtils.sendEvent(BMDataContext.BEIMI_GAME_LASTHANDS, board, gameRoom);
		CacheHelper.getGameRoomCacheBean().put(gameRoom.getId(), gameRoom, gameRoom.getOrgi());
		// 接下来就是结算，摊牌,改变状态机的状态
		log.info("10秒钟执行结算·······················");
		super.getGame(gameRoom.getPlayway(), orgi).change(gameRoom, BeiMiGameEvent.ALLCARDS.toString(),
				BMDataContext.GAME_WAIT_TIME);
	}

	private long timer;
	private GameRoom gameRoom = null;
	private String orgi;

	public NiuniuBeginTask(long timer, GameRoom gameRoom, String orgi) {
		super();
		this.timer = timer;
		this.gameRoom = gameRoom;
		this.orgi = orgi;
	}

	@Override
	public long getCacheExpiryTime() {
		return System.currentTimeMillis() + timer * 1000; // 5秒后执行
	}

}
